use axum::{
    extract::Query, routing::{get, post}, Router
};
use serde::Deserialize;

use crate::{
    error::AppErr, server::model::{cbor_ok, Cbor, CborRet, Verify, Void}, store::firm_type::{self, TbFirmType}
};

#[derive(Debug, Deserialize)]
struct CreateReq {
    proj_id: i64,
    name: String,
    description: String,
    version: u32,
    ty: String,
    target: String,
}

async fn on_create(_v: Verify, req: Cbor<CreateReq>) -> CborRet<i64> {
    let id = firm_type::create(
        req.proj_id,
        &req.name,
        &req.description,
        req.version,
        &req.ty,
        &req.target
    )
    .await?;

    cbor_ok(id)
}

#[derive(Debug, Deserialize)]
struct ProjIdReq {
    proj_id: i64
}

async fn on_query(req: Query<ProjIdReq>) -> CborRet<Box<[TbFirmType]>> {
    let items = firm_type::query(req.proj_id).await?;
    cbor_ok(items)
}

async fn on_delete(_v: Verify, firm_type: Cbor<i64>) -> Result<Void, AppErr> {
    firm_type::delete(firm_type.0).await?;
    Ok(Void)
}

pub fn register() -> Router {
    Router::new()
        .route("/create", post(on_create))
        .route("/query", get(on_query))
        .route("/delete", post(on_delete))
}
